#include "User.h"

int User::counter = 0;

void User::createSem()
{

	if ((semid = semget(ftok(".", 35 + counter), 1, IPC_CREAT | 0666)) == -1)
	{
		perror("blad przydzielenia semafora");
		exit(-1);
	}

	semctl(semid, 0, SETVAL, (int) 1);

	if ((semid2 = semget(ftok(".", 100 + counter), 1, IPC_CREAT | 0666)) == -1)
	{
		perror("blad przydzielenia semafora");
		exit(-1);
	}

	semctl(semid2, 0, SETVAL, (int) 0);

}

User::~User()
{
	semctl(semid, 0, IPC_RMID);
	semctl(semid2, 0, IPC_RMID);
}

void User::sendToClient(int code)
{
	opusc(semid, 0);
	buffer.push(new Package(code));
	podnies(semid2, 0);

	podnies(semid, 0);
}
;

void User::sendToClient(int code, string msg)
{
	opusc(semid, 0);
	buffer.push(new ChatPackage(code, msg));
	podnies(semid2, 0);
	podnies(semid, 0);
}

void User::sendToClient(int code, char *tab)
{
	opusc(semid, 0);
	buffer.push(new ImagePackage(code, tab));
	podnies(semid2, 0);
	podnies(semid, 0);
}

void User::sendToClient(int code, int val)
{
	opusc(semid, 0);
	buffer.push(new NumberPackage(code, val));
	podnies(semid2, 0);
	podnies(semid, 0);
}
;

Package * User::messageFromBuffer()
{
	Package *pack = NULL;
	opusc(semid2, 0);
	opusc(semid, 0);

	if (buffer.size() > 0)
	{
		pack = buffer.front();
		buffer.pop();
	}
	podnies(semid, 0);
	return pack;
}
